package org.jiucheng.magpiebridge.server.aio;

import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;

import org.jiucheng.magpiebridge.server.aio.proxy.ProxyClientCompletionHandler;

public class ClientWriteCompletionHandler implements CompletionHandler<Integer, ClientWriteAttachment> {
    
    public void completed(Integer result, ClientWriteAttachment attachment) {
        if (attachment.getWriteBuffer().hasRemaining()) {
            attachment.getProxyAttachment().getClientAttachment().getAsynchronousSocketChannel().write(attachment.getWriteBuffer(), attachment, this);
            return;
        }
        
        attachment.getProxyAttachment().getClientAttachment().writed.compareAndSet(true, false);
        
        if (attachment.getProxyAsynchronousSocketChannel() != null) {
            attachment.setReadByteBuffer(ByteBuffer.allocate(4 * 1024 * 1024));
            attachment.getProxyAsynchronousSocketChannel().read(attachment.getReadByteBuffer(), attachment, new ProxyClientCompletionHandler());
        }
    }

    public void failed(Throwable exc, ClientWriteAttachment attachment) {
        attachment.getProxyAttachment().getClientAttachment().writed.compareAndSet(true, false);
        exc.printStackTrace();
    }
}
